package com.vinda.ucvcamera;

import android.Manifest;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.serenegiant.common.BaseActivity;
import com.serenegiant.common.OnPermissionResponseListener;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.DeviceFilter;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.usbcameracommon.UVCCameraHandler;
import com.serenegiant.usbcameracommon.UvcCameraDataCallBack;
import com.serenegiant.widget.CameraViewInterface;
import com.yuan.camera.R;

import java.util.ArrayList;
import java.util.List;

public class MainActivity3 extends BaseActivity {
    protected USBMonitor mUSBMonitor;
    private TextView text_context;
    Button text_update, text_connect;
    private List<UsbDevice> deviceList;
    private CameraViewInterface mUVCCameraViewFirst;
    private static final float[] BANDWIDTH_FACTORS = {0.5f, 0.5f};
    private UVCCameraHandler mHandlerFirst;


    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity3_main);

        text_context = findViewById(R.id.text_context);
        text_update = findViewById(R.id.text_update);
        text_connect = findViewById(R.id.text_connect);
        mUVCCameraViewFirst = (CameraViewInterface) findViewById(R.id.camera_view_first);

        //监听Usb设备
        if (mUSBMonitor == null)
            try {
                mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
            } catch (final ClassCastException e) {
            } catch (final NullPointerException e) {
            }
        text_update.setOnClickListener(v -> {
            final List<DeviceFilter> filter = DeviceFilter.getDeviceFilters(MainActivity3.this, R.xml.device_filter);
            deviceList = mUSBMonitor.getDeviceList(filter.get(0));
            List<String> list = new ArrayList<>();
            String str = "";
            if (deviceList != null && deviceList.size() != 0) {
                for (int i = 0; i < deviceList.size(); i++) {
                    list.add(String.format("UVC Camera:(%x:%x:%s)", deviceList.get(i).getVendorId(), deviceList.get(i).getProductId(), deviceList.get(i).getDeviceName()));
                    str = str + "\n" + String.format("UVC Camera:(%x:%x:%s)", deviceList.get(i).getVendorId(), deviceList.get(i).getProductId(), deviceList.get(i).getDeviceName());
                }
                text_context.setText(str);
            }
        });

        text_connect.setOnClickListener(v -> {
            //已经有权限，可以直接显示悬浮窗
            requestPermission(new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,

            }, new OnPermissionResponseListener() {
                @Override
                public void onSuccess(String[] permissions) {
                    if (deviceList.get(0) instanceof UsbDevice) {
                        mUSBMonitor.requestPermission((UsbDevice) deviceList.get(0));
                        //判断是否显示组件
                    }
                }

                public void onFail() {
                    Toast.makeText(MainActivity3.this, "获取权限失败", Toast.LENGTH_SHORT).show();
                }
            });
        });

        mHandlerFirst = UVCCameraHandler.createHandler(this, mUVCCameraViewFirst
                , UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT
                , BANDWIDTH_FACTORS[0], new UvcCameraDataCallBack() {
                    @Override
                    public void getData(byte[] data) {
                        Log.v("zdl", "数据回调:" + data.length);
                    }
                });

    }

    @Override
    protected void onStart() {
        super.onStart();
        mUSBMonitor.register();
    }

    private final USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
        @Override
        public void onAttach(final UsbDevice device) {
            Log.d("zdl", "========onAttach======");
            Toast.makeText(MainActivity3.this, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
            Log.d("zdl", "========onConnect======");
            Toast.makeText(MainActivity3.this, "设备连接成功", Toast.LENGTH_SHORT).show();
            //设备连接成功
            if (!mHandlerFirst.isOpened()) {
                mHandlerFirst.open(ctrlBlock);
                final SurfaceTexture st = mUVCCameraViewFirst.getSurfaceTexture();
                mHandlerFirst.startPreview(new Surface(st));
            }
        }

        @Override
        public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) {
            Log.d("zdl", "========onDisconnect======");
            Toast.makeText(MainActivity3.this, "onDisconnect:" + device, Toast.LENGTH_SHORT).show();
//            if ((mHandlerFirst != null) && !mHandlerFirst.isEqual(device)) {
//                queueEvent(new Runnable() {
//                    @Override
//                    public void run() {
//                        mHandlerFirst.close();
//                        if (mFirstPreviewSurface != null) {
//                            mFirstPreviewSurface.release();
//                            mFirstPreviewSurface = null;
//                        }
////                        setCameraButton();
//                    }
//                }, 0);
//            }
        }

        @Override
        public void onDettach(final UsbDevice device) {
            Log.d("zdl", "========onDettach======");
            Toast.makeText(MainActivity3.this, "USB_DEVICE_DETACHED:" + device, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(final UsbDevice device) {
            Log.d("zdl", "========onCancel======");
            Toast.makeText(MainActivity3.this, "onCancel:" + device, Toast.LENGTH_SHORT).show();
        }
    };
}